namespace OneWorks.Utils.FluentData
{
    using System;

    internal class QueryCustomEntityHandler<TEntity> : IQueryTypeHandler<TEntity>
    {
        private readonly AutoMapper _autoMapper;
        private readonly DbCommandData _data;

        public QueryCustomEntityHandler(DbCommandData data)
        {
            this._data = data;
            this._autoMapper = new AutoMapper(this._data, typeof(TEntity));
        }

        public bool IterateDataReader { get { return true; } }

        public object HandleType(Action<TEntity, IDataReader> customMapperReader, Action<TEntity, dynamic> customMapperDynamic)
        {
            var item = (TEntity)this._data.Context.Data.EntityFactory.Create(typeof(TEntity));

            if (customMapperReader != null)
                customMapperReader(item, this._data.Reader);
            else if (customMapperDynamic != null)
                customMapperDynamic(item, new DynamicDataReader(this._data.Reader.InnerReader));
            else
                this._autoMapper.AutoMap(item);
            return item;
        }
    }
}